package vn.vfriends.id.bean;

import java.io.Serializable;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.id.jpa.entity.User;
import vn.vfriends.id.service.AccountService;
import vn.vfriends.id.service.UserService;
import vn.vfriends.id.util.MessageUtil;
import vn.vfriends.id.util.StringUtil;

/**
 *
 * @author tuan@vfriends.vn
 */
@Named
@RequestScoped
public class VerificationBean implements Serializable {

    static Logger logger = LoggerFactory.getLogger(VerificationBean.class);
    
    private String key;
    
    private String message;
    
    @Inject private UserService userService;
    
    @Inject private AccountService accountService;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getMessage() {
        return message;
    }
    
    public void preRenderAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            if (StringUtil.isEmpty(key)) {
                this.message = MessageUtil.getLocaleString("verification", "msg.keyInvalid", null, context.getViewRoot().getLocale());
            } else {
                User user = this.userService.findByVerificationKey(key);
                if (user == null) {
                    this.message = MessageUtil.getLocaleString("verification", "msg.keyNotFound", null, context.getViewRoot().getLocale());
                } else {
                    user.setActivated(true);
                    user.setVerificationKey("");
                    
                    //  Generate CIF for customer
                    String cif = accountService.generateCif(user.getId(), new Long(1000));
                    user.setCif(cif);
                    
                    this.userService.edit(user);
                    this.message = MessageUtil.getLocaleString("verification", "msg.successfully", null, context.getViewRoot().getLocale());
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));
        }
    }
}
